package com.example.opcdemo.opc;

import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.milo.opcua.sdk.client.OpcUaClient;
import org.eclipse.milo.opcua.stack.core.types.builtin.DataValue;
import org.eclipse.milo.opcua.stack.core.types.builtin.NodeId;
import org.eclipse.milo.opcua.stack.core.types.enumerated.TimestampsToReturn;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@Slf4j
@RestController
@RequiredArgsConstructor
public class OpcRest {

    private final UaOpcServiceImpl uaOpcService;

    @PostMapping("test")
    public Map<String, Object> test(@RequestBody BizOpcInfo info) {
        log.info("连接开始===》 {}", JSONObject.toJSONString(info));
        return uaOpcService.readValue(info);
    }


    @PostMapping("test1")
    public Map<String, Object> test1(@RequestBody BizOpcInfo info) {
        try {
            log.info("连接开始===》 {}", JSONObject.toJSONString(info));
            OpcUaClient opcUaClient = uaOpcService.createClient1(info.getOpcUrl());
            //开启连接
            opcUaClient.connect().get();
            //读
            readNode(opcUaClient, info);
            log.info("连接结束===》");

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 读取节点数据
     *
     * @param client OPC UA客户端
     * @throws Exception
     */
    private void readNode(OpcUaClient client, BizOpcInfo info) throws Exception {
        int namespaceIndex = 2;
        String identifier = info.getKeyType1();
        //节点
        NodeId nodeId = new NodeId(namespaceIndex, identifier);
        //读取节点数据
        DataValue value = client.readValue(0.0, TimestampsToReturn.Neither, nodeId).get();
        //标识符
        identifier = String.valueOf(nodeId.getIdentifier());
        log.info("读取数据" + identifier + ": " + String.valueOf(value.getValue().getValue()));
    }


    @PostMapping("test2")
    public Map<String, Object> test2(@RequestBody BizOpcInfo info) {
        log.info("连接开始===》 {}", JSONObject.toJSONString(info));
        try {
            OpcUaClient uaClient = OpcUtils.createUaClient(info.getOpcUrl());
            uaClient.connect().get();
            readNode(uaClient, info);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return uaOpcService.readValue(info);
    }
}
